/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.policy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.javlov.Option;
import net.javlov.Policy;
import net.javlov.State;
import net.javlov.vf.OptionValues;

/**
 * Current impl only works when all options are allowed for every state.
 * 
 * @author Matthijs Snel
 *
 */
public class FixedPolicy<T> implements Policy<T> {

	protected Map<State<T>, double[]> probs, //probabilities
									cumprobs; //cumulative probabilities
	
	protected List<Option<T>> options;
	
	public FixedPolicy(List<? extends Option<T>> options) {
		probs = new HashMap<State<T>, double[]>();
		cumprobs = new HashMap<State<T>, double[]>();
		this.options.addAll(options);
	}
	
	public void setOptionProbabilities(State<T> s, double[] p) {
		if ( p.length != options.size() )
			throw new IllegalArgumentException("Length of probability array must equal the number of possible options");
		
		probs.put(s, p);
		double[] cp = new double[p.length];
		cp[0] = p[0];
		for ( int i = 1; i < p.length; i++ )
			cp[i] = cp[i-1] + p[i];
		cumprobs.put(s, cp);
	}
	
	/*** Interface overrides ***/
	@Override
	public Option<T> getOption(State<? extends T> s) {
		double cp[] = cumprobs.get(s);
		if ( cp == null || cp.length == 0 )
			throw new UnknownStateException("No mapping for state " + s);
		
		double r = Math.random();
		int i;
		for ( i = 0; i < cp.length; i++ )
			if ( r < cp[i] )
				break;
		return options.get(i);
	}

	@Override
	public Option<T> getOption(State<? extends T> s, OptionValues qvalues) {
		return getOption(s);
	}

	@Override
	public double[] getOptionProbabilities(State<? extends T> s, OptionValues qvalues) {
		double p[] = probs.get(s);
		if ( p == null || p.length == 0 )
			throw new UnknownStateException("No mapping for state " + s);
		return p;
	}

	@Override
	public void init() {
		probs.clear(); cumprobs.clear();
	}

	@Override
	public void reset() {
		init();		
	}
	
	public static class UnknownStateException extends RuntimeException {

		private static final long serialVersionUID = 7020296302777564703L;
		
		public UnknownStateException() {}
		
		public UnknownStateException(String msg) {
			super(msg);
		}
		
	}

}
